package com.module_video.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.utls.glide.GlideConfig;
import com.luck.picture.lib.tools.ToastManage;
import com.module_video.R;
import com.module_video.bean.CircleLikesBean;
import com.module_video.bean.VideoDetailCommentBean;
import com.module_video.bean.VideoDetailSecondCommentBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2020/5/12 0012.
 */

public class CommentExpandAdapter extends BaseExpandableListAdapter {

    private static final String TAG = "CommentExpandAdapter";
    private List<VideoDetailCommentBean.ObjBean.RowsBean> commentBeanList;
    private Context context;

    //用于区分发表二级评论与回复二级评论
    public int replyType = -1;

    public CommentExpandAdapter(Context context, List<VideoDetailCommentBean.ObjBean.RowsBean> commentBeanList) {
        this.context = context;
        this.commentBeanList = commentBeanList;
    }

    @Override
    public int getGroupCount() {
        return commentBeanList.size();
    }

    @Override
    public int getChildrenCount(int i) {

        if (commentBeanList.get(i).getSecondCommentBeans() == null) {
            return 0;
        } else {
            return commentBeanList.get(i).getSecondCommentBeans().size() > 0 ? commentBeanList.get(i).getSecondCommentBeans().size() : 0;
        }

    }

    @Override
    public Object getGroup(int i) {
        return commentBeanList.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return commentBeanList.get(i).getSecondCommentBeans().get(i1);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return getCombinedChildId(groupPosition, childPosition);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpand, View convertView, ViewGroup viewGroup) {
        final GroupHolder groupHolder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_comment_1, viewGroup, false);
            groupHolder = new GroupHolder(convertView);
            convertView.setTag(groupHolder);
        } else {
            groupHolder = (GroupHolder) convertView.getTag();
        }

        Glide.with(context)
                .applyDefaultRequestOptions(GlideConfig.getCircleOptions())
                .load(commentBeanList.get(groupPosition).getUser_icon())
                .into(groupHolder.ivUser);

        groupHolder.tv_name.setText(commentBeanList.get(groupPosition).getUser_name());
        groupHolder.tv_time.setText(commentBeanList.get(groupPosition).getComment_date());
        groupHolder.tv_content.setText(commentBeanList.get(groupPosition).getComment_content());

        initIvZanState(groupHolder.iv_zan, commentBeanList.get(groupPosition).getLike_status());
        groupHolder.tv_zan.setText(commentBeanList.get(groupPosition).getLike_total() + "");
        groupHolder.iv_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //发送评论点赞状态至服务器
                sendLikeStateToService(groupHolder.iv_zan, groupHolder.tv_zan, "comment_id", commentBeanList.get(groupPosition).getComment_id());
            }
        });

        return convertView;
    }


    @Override
    public View getChildView(final int groupPosition, int childPosition, boolean b, View convertView, ViewGroup viewGroup) {
        final ChildHolder childHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_reply, viewGroup, false);
            childHolder = new ChildHolder(convertView);
            convertView.setTag(childHolder);
        } else {
            childHolder = (ChildHolder) convertView.getTag();
        }

        replyType = -1;

        VideoDetailSecondCommentBean.ObjBean.RowsBean replyBean = null;
        if (commentBeanList.get(groupPosition).getSecondCommentBeans() != null)
            replyBean = (VideoDetailSecondCommentBean.ObjBean.RowsBean) commentBeanList.get(groupPosition).getSecondCommentBeans().get(childPosition);

        Glide.with(context)
                .applyDefaultRequestOptions(GlideConfig.getCircleOptions())
                .load(replyBean.getUser_icon())
                .into(childHolder.replyIvUser);

        childHolder.replyTv_time.setText(replyBean.getReply_date());

        initIvZanState(childHolder.replyIv_zan, replyBean.getLike_status());
        childHolder.replyTv_zan.setText(replyBean.getLike_total() + "");
        final VideoDetailSecondCommentBean.ObjBean.RowsBean finalReplyBean = replyBean;
        childHolder.replyIv_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //发送二级评论或回复二级评论点赞状态至服务器
                sendLikeStateToService(childHolder.replyIv_zan, childHolder.replyTv_zan, "reply_id", finalReplyBean.getReply_id());
            }
        });

        //获取评论的用户名
        String replyUser = "";
        replyUser = replyBean.getUser_name();
        childHolder.replyTv_name.setText(replyUser);
        //根据回复数据中是否有Up_reply_id来判断是二级评论还是回复二级评论
        if (StringUtil.isNotEmpty(replyBean.getUp_reply_id(), true)) {
            replyType = 3;
        } else {
            replyType = 2;
        }
        if (replyType > -1) {
            //发布二级评论
            if (2 == replyType) {
                childHolder.replyTv_content.setText(replyBean.getReply_content());
            } else if (3 == replyType) {//回复二级评论
                childHolder.replyTv_content.setText("回复 " + " @ " + replyUser + " : " + replyBean.getReply_content());
            }
        }

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    private class GroupHolder {
        private ImageView ivUser;
        private TextView tv_name, tv_content, tv_time, tv_zan;
        private ImageView iv_zan;

        public GroupHolder(View view) {
            ivUser = (ImageView) view.findViewById(R.id.comment_iv_cover);
            tv_content = (TextView) view.findViewById(R.id.comment_tv_msg);
            tv_name = (TextView) view.findViewById(R.id.comment_tv_name);
            tv_time = (TextView) view.findViewById(R.id.comment_tv_time);
            iv_zan = (ImageView) view.findViewById(R.id.comment_iv_zan);
            tv_zan = (TextView) view.findViewById(R.id.comment_tv_num);
        }
    }

    private class ChildHolder {
        private ImageView replyIvUser;
        private TextView replyTv_name, replyTv_content, replyTv_time, replyTv_zan;
        private ImageView replyIv_zan;

        public ChildHolder(View view) {
            replyIvUser = (ImageView) view.findViewById(R.id.reply_iv_cover);
            replyTv_content = (TextView) view.findViewById(R.id.reply_tv_msg);
            replyTv_name = (TextView) view.findViewById(R.id.reply_tv_name);
            replyTv_time = (TextView) view.findViewById(R.id.reply_tv_time);
            replyIv_zan = (ImageView) view.findViewById(R.id.reply_iv_zan);
            replyTv_zan = (TextView) view.findViewById(R.id.reply_tv_num);
        }
    }


    /**
     * by moos on 2018/04/20
     * func:评论成功后插入一条数据
     *
     * @param commentDetailBean 新的评论数据
     */
    public void addTheCommentData(VideoDetailCommentBean.ObjBean.RowsBean commentDetailBean) {
        if (commentDetailBean != null) {

            commentBeanList.add(commentDetailBean);
            notifyDataSetChanged();
        } else {
            throw new IllegalArgumentException("评论数据为空!");
        }

    }

    /**
     * by moos on 2018/04/20
     * func:回复成功后插入一条数据
     *
     * @param replyDetailBean 新的回复数据
     */
    public void addTheReplyData(VideoDetailSecondCommentBean.ObjBean.RowsBean replyDetailBean, int groupPosition) {
        if (replyDetailBean != null) {
            Log.e(TAG, "addTheReplyData: >>>>该刷新回复列表了:" + replyDetailBean.toString());
            if (commentBeanList.get(groupPosition).getSecondCommentBeans() != null) {
                commentBeanList.get(groupPosition).getSecondCommentBeans().add(replyDetailBean);
            } else {
                List<VideoDetailSecondCommentBean.ObjBean.RowsBean> replyList = new ArrayList<>();
                replyList.add(replyDetailBean);
                commentBeanList.get(groupPosition).setSecondCommentBeans(replyList);
            }
            notifyDataSetChanged();
        } else {
            throw new IllegalArgumentException("回复数据为空!");
        }

    }

    /**
     * by moos on 2018/04/20
     * func:添加和展示所有回复
     *
     * @param replyBeanList 所有回复数据
     * @param groupPosition 当前的评论
     */
    private void addReplyList(List<VideoDetailSecondCommentBean.ObjBean.RowsBean> replyBeanList, int groupPosition) {
        if (commentBeanList.get(groupPosition).getSecondCommentBeans() != null) {
            commentBeanList.get(groupPosition).getSecondCommentBeans().clear();
            commentBeanList.get(groupPosition).getSecondCommentBeans().addAll(replyBeanList);
        } else {

            commentBeanList.get(groupPosition).setSecondCommentBeans(replyBeanList);
        }

        notifyDataSetChanged();
    }


    /**
     * 设置值区分发布二级与回复二级
     *
     * @param replyType
     */
    public void setReplyType(int replyType) {
        if (replyType > -1) {
            this.replyType = replyType;
        }
    }

    /**
     * 设置点赞图标的状态
     *
     * @param ivZan
     * @param zanState
     */
    public void initIvZanState(ImageView ivZan, int zanState) {
        if (1 == zanState) {
            ivZan.setImageResource(R.mipmap.circle_icon_like_s_have);
        } else if (0 == zanState) {
            ivZan.setImageResource(R.mipmap.circle_icon_like_s_none);
        }
    }


    /**
     * 设置点赞数据到服务器
     *
     * @param requstStr  请求接口地址 comment_id代表评论点赞   reply_id代表二级评论以及回复点赞
     * @param comment_id 该评论或回复的id
     */
    private void sendLikeStateToService(final ImageView ivLike, final TextView tvZanNum, String requstStr, int comment_id) {

        String requestType = "";
        if ("comment_id".equals(requstStr)) {
            requestType = "DYNAMIC_COMMENT_LIKE";
        } else if ("reply_id".equals(requstStr)) {
            requestType = "DYNAMIC_REPLY_LIKE";
        }

        LogUtil.e("请求接口为：" + requstStr + "评论或回复Id为：" + comment_id);
        if (comment_id != 0)
            HttpUtils.with(context)
                    .addParam("requestType", requestType)
                    .addParam(requstStr, comment_id)
                    .addParam("token", SharedPreferenceManager.getInstance(context).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<CircleLikesBean>() {
                        @Override
                        public void onSuccess(CircleLikesBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                int zan = result.getObj().getLike_status();
                                initIvZanState(ivLike, zan);
                                ToastManage.s(context, result.getMsg());

                                tvZanNum.setText(result.getObj().getLike_total() + "");

                            } else {
                                ToastManage.s(context, result.getMsg());
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });

    }

}
